/*
 *  txdnet.cn tonydon
 * 
 */
package cn.txdnet.txcms.admin.action;

import cn.txdnet.txweb.model.ModelUtil;
import cn.txdnet.txweb.model.ModelView;
import cn.txdnet.txweb.utils.HttpUtil;
import cn.txdnet.txweb.utils.Message;
import cn.txdnet.txweb.utils.WebUtil;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import txdnet.util.FileUtil;
import txdnet.util.StaticMark;

/**
 *
 * @author txdnet
 */
public class PageSetAction {

    /**
     * 读取页面数据
     * @param req
     * @return 
     */
    public ModelView read_page(HttpServletRequest req) {
        String pageUrl = WebUtil.getNoNull(req, "pageUrl", null);
        String charset = WebUtil.getNoNull(req, "charset", StaticMark.ENCODING_UTF8);
        if (pageUrl == null) {
            return ModelUtil.getTextModel(Message.MSG_PARAM_ERR);
        }
        String pageContent = HttpUtil.doGet(pageUrl, charset, null, null);
        return ModelUtil.getTextModel(pageContent);
    }

    /**
     * 保存页面数据到本地或提交到远端保存
     * @param req
     * @return
     * @throws Exception 
     */
    public ModelView save_page(HttpServletRequest req) throws Exception {
        String postUrl = WebUtil.getNoNull(req, "postUrl", null);
        String savePath = WebUtil.getNoNull(req, "savePath", null);
        String charset = WebUtil.getNoNull(req, "charset", StaticMark.ENCODING_UTF8);
        String pageContent = WebUtil.getNoNull(req, "pageContent", null);

        if ((postUrl == null && savePath == null) || pageContent == null) {
            return ModelUtil.getTextModel(Message.MSG_FIELD_ERR);
        }
        String responseTxt = "处理结果: ";
        if (postUrl != null) {
            Map<String, String> params = new HashMap<String, String>(1);
            params.put("pageContent", URLEncoder.encode(pageContent, charset));
            responseTxt = responseTxt.concat(HttpUtil.doPost(postUrl, charset, params, null, null).trim());
        }
        if (savePath != null) {
            String realSavePath = WebUtil.WEB_APP_PATH.concat(savePath);
            if (FileUtil.writeStringToFile(realSavePath, pageContent, charset)) {
                responseTxt = responseTxt.concat("\n本地保存页面成功！");
            } else {
                responseTxt = responseTxt.concat("\n本地保存页面失败！");
            }
        }
        return ModelUtil.getTextModel(responseTxt);
    }
}
